package pl.alef.mindplay.services.impl;

import java.util.List;

import org.perf4j.aop.Profiled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.alef.mindplay.dao.RefererDAO;
import pl.alef.mindplay.dao.UserAgentDAO;
import pl.alef.mindplay.dao.VisitDAO;
import pl.alef.mindplay.dao.VisitorDAO;
import pl.alef.mindplay.model.Referer;
import pl.alef.mindplay.model.UserAgent;
import pl.alef.mindplay.model.Visit;
import pl.alef.mindplay.services.VisitService;

@Service("visitService")
public class VisitServiceImpl implements VisitService {

	final static Logger logger = LoggerFactory.getLogger(VisitServiceImpl.class);
	
	@Autowired
	@Qualifier("visitDAO")
	protected VisitDAO visitDAO;
	
	@Autowired
	protected UserAgentDAO userAgentDAO;
	
	@Autowired
	protected VisitorDAO visitorDAO;
	
	@Autowired
	protected RefererDAO refererDAO;
	
	
	@Profiled
	@Transactional(readOnly=true)
	public List<Visit> list() {
		List<Visit> list = visitDAO.queryAll();
		return list;
	}

	@Transactional(readOnly=false)
	public void save(Visit visit) {
		
		logger.debug("Visit to save : {}", visit);
		
		if(visit.getUserAgent() != null) {
			userAgentDAO.save(visit.getUserAgent());
		}
		if(visit.getReferer() != null) {
			refererDAO.save(visit.getReferer());
		}
		visitorDAO.save(visit.getVisitor());		
		visitDAO.save(visit);
		logger.debug("visit saved - id = {}", visit.getId());		
	}

	@Transactional(readOnly=true)
	public UserAgent getUserAgentByName(String userAgentName) {
		if(userAgentName == null || "".equals(userAgentName.trim())) {
			return null;
		} 
		
		UserAgent userAgent = userAgentDAO.findByName(userAgentName);
		if(userAgent == null) {
			logger.debug("Create new user agent ..");
			userAgent = new UserAgent(userAgentName);
		}
		return userAgent;
	}
	

	@Transactional(readOnly=true)
	public Referer getRefererByName(String refererName) {
		if(refererName == null || "".equals(refererName.trim())) {
			return null;
		} 		
		
		Referer referer = refererDAO.findByName(refererName);
		if(referer == null) {
			logger.debug("Create new referer ..");
			referer = new Referer(refererName);
		} 
		return referer;
	}	
	
}
